<?php


namespace frontend\models;

use common\models\UserModel;
use yii\base\model;
use yii;
/**
 * User form
 */
class UserForm extends model
{
    public $id;
    public $username;
    public $email;
    public $head_img;
    public $password_hash;
    /**
     * 定义场景
     * SCENARIO_CREATE 创建场景
     * SCENARIO_UPDATE 更新场景
     */
    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';
    /**
     * 场景设置
     * @return array|array[]
     */
    public function scenarios()
    {
        $scenarios = [
            self::SCENARIO_CREATE => ['username', 'email', 'head_img'],
            self::SCENARIO_UPDATE => ['username', 'email', 'head_img']
        ];
        return array_merge(parent::scenarios(), $scenarios); // TODO: Change the autogenerated stub
    }
    public function rules()
    {
        return [
            [['id','username', 'email', 'head_img'], 'required'],
        ]; // TODO: Change the autogenerated stub
    }
    public function attributeLabels()
    {
        return [
            'id' => '编码',
            'username' => '用户名',
            'email' => '邮箱',
            'head_img' => '头像',
            'password_hash' => '密码'
        ]; // TODO: Change the autogenerated stub
    }
    /**
     * 用户资料编辑
     * @return bool
     */
    public function edit()
    {
        if (!(yii::$app->user->identity->getId())) {
            throw new \Exception('未登录！');
        }

        $model = UserModel::findOne(yii::$app->user->identity->getId());
        $model->setAttributes($this->attributes);
//        $model->username = $this->attributes['username'];
//        var_dump($model);die;
        if (!$model->save()) {
            throw new \Exception('文章编辑失败');
        }

        return true;

    }
    /**
     * 用户资料获取
     * @return bool
     */
    public function getItem($user_id)
    {
        $res = UserModel::findOne($user_id);

        return $res;
    }
    /**
     * 用户密码设置
     * @return bool
     */
    public function SetPwd($password){
        $model = UserModel::findOne(yii::$app->user->identity->getId());
        $model->setPassword($password);
        $model->generateAuthKey();
//        echo $model->auth_key.'//';
//        echo $model->password_hash;die;
        if (!$model->save()) {
            throw new \Exception('重置密码失败');
        }
        return true;
    }
}
